package com.gimi.test_jpa.com.gimi.service.customer;


import cn.hutool.core.bean.BeanUtil;
import com.gimi.test_jpa.com.gimi.dto.customer.CustomerDto;
import com.gimi.test_jpa.com.gimi.entity.customer.CustomerEntity;
import com.gimi.test_jpa.com.gimi.jpa.customer.CustomerJpa;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;



@Service
@Transactional(rollbackFor = Exception.class)
public class CustomerService {
    @Autowired
    private CustomerJpa customerJpa;

    /**
     * 创建修改客户
     *
     * @param dto
     * @return
     */
    public Boolean createAndUpdateCus(CustomerDto dto) {
        if (dto.getCusId() != null) {
            CustomerEntity customerJpaById = customerJpa.queryByCusId(dto.getCusId());;
            if (customerJpaById != null){
                String cusIdCard = customerJpaById.getCusIdCard();
                if (!dto.getCusIdCard().equals(customerJpaById.getCusIdCard())) {
                    throw new RuntimeException("身份证号不能修改");
                }
                CustomerEntity customerEntity = new CustomerEntity();
                BeanUtil.copyProperties(dto, customerEntity);
//        BeanUtils.copyPropertiesIgnoreNull(dto,customerEntity);
                customerJpa.save(customerEntity);
                return true;
            }
        }
        if (dto.getCusIdCard() != null) {
            CustomerEntity byCusIdCard = customerJpa.findByCusIdCard(dto.getCusIdCard());
            if (byCusIdCard != null)
                throw new RuntimeException("该账客户(身份证号)已存在");
        }
        CustomerEntity customerEntity = new CustomerEntity();
        BeanUtil.copyProperties(dto, customerEntity);
//        BeanUtils.copyPropertiesIgnoreNull(dto, customerEntity);
        customerEntity.setAddTime(new Date());
        customerJpa.save(customerEntity);
        return true;
    }


    /**
     * 根据客户Id 删除客户
     * @param cusId
     * @return
     */
    public Boolean deleteCus(String cusId){
        CustomerEntity customerEntity = customerJpa.queryByCusId(cusId);
        if (customerEntity==null){
            throw new RuntimeException("该客户不存在");
        }
        customerJpa.deleteById(cusId);
        return true;
    }

    /**
     * 根据客户Id查询客户信息
     * @param cusId
     * @return
     */
    public CustomerDto findByCusId(String cusId){
        CustomerEntity customerEntity = customerJpa.queryByCusId(cusId);
        if (customerEntity==null){
            throw new RuntimeException("该客户不存在");
        }
        CustomerDto customerDto = new CustomerDto();
        BeanUtil.copyProperties(customerEntity,customerDto);
//        BeanUtils.copyPropertiesIgnoreNullAndEmptyStr(customerEntity,customerDto);
        return customerDto;
    }
}
